﻿
using System;
using System.IO.Ports;
using System.Windows.Input;
using System.Windows.Threading;

namespace 五味子串口调试助手3
{
    public class OpenCommCommand : ICommand
    {
        public MainWindowModel ViewModel { get; set; }

        public OpenCommCommand(MainWindowModel ViewModel)
        {
            this.ViewModel = ViewModel;
        }
        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            if (!ViewModel.commIsOpen)
            {
                ViewModel.serialPort = new SerialPort();
                ViewModel.serialPort.PortName = ViewModel.commPort;
                ViewModel.serialPort.BaudRate = ViewModel.bandRate;
                ViewModel.serialPort.Parity = (Parity)System.Enum.Parse(typeof(Parity), ViewModel.verfyBits);
                ViewModel.serialPort.DataBits = ViewModel.dataBits;
                ViewModel.serialPort.StopBits = (StopBits)ViewModel.stopBits;
                ViewModel.serialPort.ReadTimeout = 17;
                try
                {
                    ViewModel.serialPort.Open();
                    ViewModel.commIsOpen = true;
                }
                catch
                {
                    ViewModel.commIsOpen = false;
                    ViewModel.serialPort.Close();
                }
            }
            else
            {
                ViewModel.commIsOpen = false;
                ViewModel.serialPort.Close();
            }

        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }
}
